# vim:ts=4:sw=4:noet:
""" Basic block optimisers """

from bbvisit import BBVisitor
import c.compiler.cfg

class OptTrim(BBVisitor):
	def doBasicBlock(self, bb):
		newst = []
		gotReturn = False
		i = 0
		while i<len(bb.statements):
			st = bb.statements[i]
			# check for store/pop pairs, and merge into a pop
			if i<(len(bb.statements)-1):
				nextst = bb.statements[i+1]
				if (isinstance(st, c.compiler.ir.IRAssign) and 
						isinstance(nextst, c.compiler.cfg.CFGEndStatement) and
						st.var.pos<8):
					st.addPop()
					i+=1
			# remove anything after a return
			if isinstance(st, c.compiler.ir.IRReturn):
				newst.append(st)
				gotReturn = True
			if not gotReturn:
				newst.append(st)
			i += 1
		bb.statements = newst
